//
//  ReadChapterView.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/14.
//

import UIKit

class ReadChapterView: UIView {
    
    lazy var chapterLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 12)
        return label
    }()
    
    lazy var pageLabel: UILabel = {
        let label = UILabel()
        label.font = .wn_font(name: .bold, size: 12)
        label.textAlignment = .right
        return label
    }()
            
    var content: NSAttributedString? {
        didSet {
            if let c = content {
                frameRef = getFrameRef(c)
            }
        }
    }

    var frameRef: CTFrame? {
        didSet {
            if frameRef != nil {
                setNeedsDisplay()
            }
        }
    }
    
    var scrollModel: ChapterPageModel? {
        didSet {
            if let s = scrollModel {
                darkModeConfig()
                frameRef = getFrameRef(s.showContent, .init(origin: .zero, size: CGSize(width: ScreenW-24, height: ScreenH)))
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(chapterLabel)
        addSubview(pageLabel)
        chapterLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.bottom.equalTo(-TabBarMargin-12)
        }
        pageLabel.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.bottom.equalTo(-TabBarMargin-12)
        }
    }
    
    func darkModeConfig() {
        backgroundColor = isDark() ? .init(named: "black_121212") : .wn_colorWithHexString("\(getReadConfigItem("bgColor"))")
        chapterLabel.textColor = isDark() ? .init(named: "gray_777777") : .black
        pageLabel.textColor = isDark() ? .init(named: "gray_777777") : .black

        let fontStr = wn_toString(getReadConfigItem("font"))
        var fontName = UIFont.ESFontName.regular
        if fontStr == "regular" {
            fontName = .regular
        }else if fontStr == "floane" {
            fontName = .floane
        }else if fontStr == "national" {
            fontName = .national
        }else if fontStr == "medium" {
            fontName = .medium
        }
        chapterLabel.font = .wn_font(name: fontName, size: 12)
        pageLabel.font = .wn_font(name: fontName, size: 12)
        layoutIfNeeded()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension ReadChapterView {
    /// 绘制
    override func draw(_ rect: CGRect) {
        if (frameRef == nil) { return }
        let ctx = UIGraphicsGetCurrentContext()
        ctx?.textMatrix = .identity
        ctx?.translateBy(x: 12, y: (getReadConfigItem("flip") as? String == "Scroll") ? ScreenH : ScreenH-TabBarMargin-(supportFaceID ? 0 : 12)) //
        ctx?.scaleBy(x: 1, y: -1)
        CTFrameDraw(frameRef!, ctx!)
    }
}

